package com.ec.au.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import static com.ec.au.constant.SysConstant.KEY_SURVIVAL_ONE_DAY;

/**
 * JWT工具类
 */
public class JwtUtil {
    private static final String SECRET_KEY = "your-256-bit-secret-must-be-at-least-32-chars";
    private static final long EXPIRATION_MS = KEY_SURVIVAL_ONE_DAY; // 24小时

    // 创建Token
    public static String createToken(String username) {
        SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

        return Jwts.builder()
                .subject(username)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION_MS))
                .signWith(key)
                .compact();
    }

    // 解析Token
    public static Claims parseToken(String token) {
        SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    // 验证Token
    public static boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (ExpiredJwtException ex) {
            // Token过期处理
        } catch (SignatureException ex) {
            // 签名无效处理
        } catch (JwtException ex) {
            // 其他JWT异常
        }
        return false;
    }
    public static void main(String[] args) throws Exception {
        String jwt=createToken("1234");
        System.out.println(jwt);
    }


}
